package com.spring.boot.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spring.boot.entity.*;
import com.spring.boot.mapper.SummaryMapper;
import com.spring.boot.service.*;
import com.spring.boot.utils.MyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class SummaryServiceImpl extends ServiceImpl<SummaryMapper, Summary> implements SummaryService {

    private final static Logger log = LoggerFactory.getLogger(SummaryServiceImpl.class);

    @Autowired
    private ChinaCityService chinaCityService;
    @Autowired
    private InOutNumService inOutNumService;
    @Autowired
    private DangerLevelService dangerLevelService;
    @Autowired
    private ProvinceService provinceService;


    @Override
    public List<Summary> buildSummary(String date) {
        List<Summary> list = new ArrayList<>();
        String part1 = buildPart1(date);
        list.add(new Summary(Integer.parseInt(date.replace("-", "") + "1"), 1, part1, date, null));
        String part2 = buildPart2(date);
        list.add(new Summary(Integer.parseInt(date.replace("-", "") + '2'), 2, part2, date, null));
        String part3 = buildPart3(date);
        list.add(new Summary(Integer.parseInt(date.replace("-", "") + '3'), 3, part3, date, null));
        String part4 = buildPart4(date);
        list.add(new Summary(Integer.parseInt(date.replace("-", "") + '4'), 4, part4, date, null));
        return list;
    }


    private List<ChinaCity> getRecentConfirm(String date) {
        QueryWrapper<ChinaCity> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("city", "confirmed_relative");
        queryWrapper.eq("pro", "福建");
        queryWrapper.between("create_time", MyUtils.getBeforeDays(date, -3), date);
        queryWrapper.orderByAsc("city_code");
        List<ChinaCity> list = chinaCityService.list(queryWrapper);
        return list;
    }

    private HashMap judgeRecentTrend(List<ChinaCity> list) {
        HashMap<String, String> resultMap = new HashMap<>();
        HashMap<String, Integer> tempMap = new HashMap<>();
        tempMap.put("莆田", 0);
        tempMap.put("厦门", 0);
        tempMap.put("漳州", 0);
        tempMap.put("泉州", 0);
        tempMap.put("福州", 0);
        tempMap.put("三明", 0);
        tempMap.put("南平", 0);
        tempMap.put("龙岩", 0);
        tempMap.put("宁德", 0);
        for (ChinaCity chinaCity : list) {
            Integer val;
            switch (chinaCity.getCity()) {
                case ("莆田"):
                    val = tempMap.get("莆田");
                    tempMap.replace("莆田", val, val + Integer.parseInt(chinaCity.getConfirmedRelative()));
                    break;
                case ("厦门"):
                    val = tempMap.get("厦门");
                    tempMap.replace("厦门", val, val + Integer.parseInt(chinaCity.getConfirmedRelative()));
                    break;
                case ("漳州"):
                    val = tempMap.get("漳州");
                    tempMap.replace("漳州", val, val + Integer.parseInt(chinaCity.getConfirmedRelative()));
                    break;
                case ("泉州"):
                    val = tempMap.get("泉州");
                    tempMap.replace("泉州", val, val + Integer.parseInt(chinaCity.getConfirmedRelative()));
                    break;
                case ("福州"):
                    val = tempMap.get("福州");
                    tempMap.replace("福州", val, val + Integer.parseInt(chinaCity.getConfirmedRelative()));
                    break;
                case ("三明"):
                    val = tempMap.get("三明");
                    tempMap.replace("三明", val, val + Integer.parseInt(chinaCity.getConfirmedRelative()));
                    break;
                case ("南平"):
                    val = tempMap.get("南平");
                    tempMap.replace("南平", val, val + Integer.parseInt(chinaCity.getConfirmedRelative()));
                    break;
                case ("龙岩"):
                    val = tempMap.get("龙岩");
                    tempMap.replace("龙岩", val, val + Integer.parseInt(chinaCity.getConfirmedRelative()));
                    break;
                case ("宁德"):
                    val = tempMap.get("宁德");
                    tempMap.replace("宁德", val, val + Integer.parseInt(chinaCity.getConfirmedRelative()));
                    break;
            }
        }

        tempMap.forEach((key, value) -> {//key 是城市名
//            if (value <= 0){
//                resultMap.put(key,"疫情目前稳定");
//            }
            if (value > 0 && value < 20) {
                resultMap.put(key, "疫情初露苗头");
            } else if (value > 20) {
                resultMap.put(key, "疫情还是严重");
            }
        });
        return resultMap;
    }

    private List<InOutNum> getAttentionCities(String date, HashMap citiesMap) {
        QueryWrapper<InOutNum> queryWrapper = new QueryWrapper<>();
        List<InOutNum> attentionCities = new ArrayList<>();
        citiesMap.forEach((key, value) -> {
            queryWrapper.clear();//清除之前的条件
            //key 是城市名
            queryWrapper.select("city_name", "value")
                    .eq("type", "out")
                    .eq("target_city", key)
                    .eq("date", date.replace("-", ""))
                    .in("city_name", "莆田市", "泉州市", "南平市", "厦门市", "漳州市", "宁德市", "三明市", "福州市", "龙岩市")
                    .gt("value", 20)
                    .orderByDesc("value");
            List<InOutNum> list = inOutNumService.list(queryWrapper);
            attentionCities.addAll(list);
        });
        return attentionCities;
    }

    private String buildPart1(String date) {
        List<ChinaCity> recentConfirm = getRecentConfirm(date);
        HashMap hashMap = judgeRecentTrend(recentConfirm);
//        StringBuilder steadyCities = new StringBuilder();
        StringBuilder beginCities = new StringBuilder();
        StringBuilder seriousCities = new StringBuilder();

        hashMap.forEach((key, value) -> {
//            if (value.equals("疫情目前稳定")){
//                steadyCities.append(key).append('、');
//            }
//            else
            if (value.equals("疫情初露苗头")) {
                beginCities.append(key).append('、');
            } else if (value.equals("疫情还是严重")) {
                seriousCities.append(key).append('、');
            }
        });
        String str1 = "就过去三天确诊情况来看，";
        if (!StrUtil.hasEmpty(beginCities.toString())) {
            str1 = str1 + beginCities.toString() + "疫情初露苗头;";
        }
        if (!StrUtil.hasEmpty(seriousCities.toString())) {
            str1 = str1 + seriousCities.toString() + "疫情还是严重。";
        }


        StringBuilder attentionCities = new StringBuilder();
        //获取需要格外注意的地区
        List<InOutNum> attentionCityList = getAttentionCities(date, hashMap);
        for (InOutNum inOutNum : attentionCityList) {
            attentionCities.append(inOutNum.getCityName()).append('、');
        }
        String str2;
        if (StrUtil.hasEmpty(attentionCities.toString())) {
            str2 = "结合迁徙大数据，应注意周边地区的防控工作。";
        } else {
            str2 = "结合迁徙大数据，应注意" + attentionCities.toString() + "地区的防控工作。";
        }
        String resultStr = str1 + str2;
        return resultStr;
    }

    private String buildPart2(String date) {
        QueryWrapper<ChinaCity> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("city")
                .likeRight("create_time", date)
                .eq("pro", "福建")
                .gt("cur_confirm", 2);
        List<ChinaCity> list = chinaCityService.list(queryWrapper);
        StringBuilder citiesStr = new StringBuilder();
        for (ChinaCity chinaCity : list) {
            citiesStr.append(chinaCity.getCity()).append('、');
        }
        String str = "目前疫情主要分布在：" + citiesStr.toString() + "地区，应注意此范围的疫情防控。";
        return str;
    }

    private String buildPart3(String date) {
        QueryWrapper<DangerLevel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("date", date);
        DangerLevel dangerLevel = dangerLevelService.getOne(queryWrapper);
        if(!ObjectUtil.isNull(dangerLevel)){
            //        Field[] fields = ReflectUtil.getFields(DangerLevel.class);//获取类的字段,这里本来想跟js一样，循环键，根据键获取值，再判断。还得学啊年轻人
            StringBuilder citiesStr = new StringBuilder();
            BigDecimal val;
            for (int i = 0; i < 8; i++) {
                switch (i) {
                    case (0):
                        val = dangerLevel.getFuzhou();
                        if (val.compareTo(new BigDecimal(1250)) > 0) {
                            citiesStr.append("福州、");
                        }
                        break;
                    case (1):
                        val = dangerLevel.getXiamen();
                        if (val.compareTo(new BigDecimal(1250)) > 0) {
                            citiesStr.append("厦门、");
                        }
                        break;
                    case (2):
                        val = dangerLevel.getNingde();
                        if (val.compareTo(new BigDecimal(1250)) > 0) {
                            citiesStr.append("宁德、");
                        }
                        break;
                    case (3):
                        val = dangerLevel.getNanping();
                        if (val.compareTo(new BigDecimal(1250)) > 0) {
                            citiesStr.append("南平、");
                        }
                        break;
                    case (4):
                        val = dangerLevel.getSanming();
                        if (val.compareTo(new BigDecimal(1250)) > 0) {
                            citiesStr.append("三明、");
                        }
                        break;
                    case (5):
                        val = dangerLevel.getQuanzhou();
                        if (val.compareTo(new BigDecimal(1250)) > 0) {
                            citiesStr.append("泉州、");
                        }
                        break;
                    case (6):
                        val = dangerLevel.getZhangzhou();
                        if (val.compareTo(new BigDecimal(1250)) > 0) {
                            citiesStr.append("漳州、");
                        }
                        break;
                    case (7):
                        val = dangerLevel.getLongyan();
                        if (val.compareTo(new BigDecimal(1250)) > 0) {
                            citiesStr.append("龙岩、");
                        }
                        break;
                    case (8):
                        val = dangerLevel.getPutian();
                        if (val.compareTo(new BigDecimal(1250)) > 0) {
                            citiesStr.append("莆田、");
                        }
                        break;
                }
            }
            String resultStr = "就危险系数来看，" + citiesStr.toString() + "发出了不同程度的预警，应当及时采取防范措施。";
            return resultStr;
        }
        else {
            log.warn("由于缺少危险等级数据，第三部分总结无法生成！");
            return "由于缺少危险等级数据，第三部分总结无法生成！";
        }

    }

    private String buildPart4(String date) {
        QueryWrapper<Province> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("cur_confirm_relative")
                .between("create_time", MyUtils.getBeforeDays(date, -3), date)
                .orderByDesc("create_time");
        List<Province> list = provinceService.list(queryWrapper);
        Integer shortTrend = 0;
        String shortTrendStr;
        for (Province province : list) {
            shortTrend += Integer.parseInt(province.getCurConfirmRelative());
        }
        if (shortTrend > 0) {
            shortTrendStr = "就近期全省总体数据来看，疫情形式日渐严峻，";
        } else if (shortTrend == 0) {
            shortTrendStr = "就近期全省总体数据来看，疫情形式较为稳定，";
        } else {
            shortTrendStr = "就近期全省总体数据来看，疫情形式有转好迹象，";
        }

        queryWrapper.clear();
        queryWrapper.select("cur_confirm_relative")
                .between("create_time", MyUtils.getBeforeDays(date, -14), date)
                .orderByDesc("create_time");
        List<Province> list2 = provinceService.list(queryWrapper);
        Integer longTrend = 0;
        String longTrendStr = "";
        for (Province province : list2) {
            longTrend += Integer.parseInt(province.getCurConfirmRelative());
        }
        if (shortTrend > 0 && longTrend > 0) {
            longTrendStr = "望各部门各单位齐心协力，攻克难关。";
        } else if (shortTrend > 0 && longTrend <= 0) {
            longTrendStr = "一波未平一波又起，望各部门之间相互配合，共度难关。";
        } else if (shortTrend <= 0 && longTrend > 0) {
            longTrendStr = "但是疫情的走向仍扑朔迷离，各单位万不可掉以轻心。";
        } else if (shortTrend <= 0 && longTrend <= 0) {
            longTrendStr = "疫情趋于稳定，各地区可适度开放。";
        }
        String resultStr = shortTrendStr + longTrendStr;
        return resultStr;
    }
}
